package dd.lo.chapter14;

import dd.lo.util.ImageUtils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 代码样例：Example 14-1. Finding contours based on a trackbar’s location; the contours are updated whenever the trackbar is moved
 */
public class C14E1 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private static final int DEFAULT_WIDTH = 1080;
    private static final int DEFAULT_HEIGHT = 768;

    private ImageView imageView;

    private Mat srcImg;

    private int gThreshold = 127;

    private void imageProcess(Mat srcImg) {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() {
                if (null == srcImg) return null;
                Mat dst = new Mat();
                Imgproc.threshold(srcImg, dst, gThreshold, 255, Imgproc.THRESH_BINARY);
                List<MatOfPoint> contours = new ArrayList<>();
                Imgproc.findContours(dst, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
                Imgproc.drawContours(dst, contours, -1, Scalar.all(255));
                //调整图片大小以用于展示
                ImageUtils.fitImgSize(dst, DEFAULT_WIDTH, DEFAULT_HEIGHT);
                MatOfByte buffer = new MatOfByte();
                Imgcodecs.imencode(".jpeg", dst, buffer);
                Platform.runLater(() -> imageView.setImage(new Image(new ByteArrayInputStream(buffer.toArray()))));
                return null;
            }
        };
        new Thread(task).start();
    }

    @Override
    public void start(Stage stage) {
        //File chooser
        Button imageChooser = new Button("选择图片");
        imageChooser.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("请选择图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Downloads")
            );
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("JPEG", "*.jpeg"),
                    new FileChooser.ExtensionFilter("WEBP", "*.webp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp")
            );
            File imgFile = fileChooser.showOpenDialog(stage);
            if (null == imgFile) {
                System.out.println("用户取消选中文件");
                return;
            }
            //读取一张图片
            srcImg = Imgcodecs.imread(imgFile.getAbsolutePath(), Imgcodecs.IMREAD_GRAYSCALE);
            if (srcImg.empty()) {
                throw new RuntimeException("图片读取失败");
            }
            imageProcess(srcImg);
        });
        //threshold indicator
        Text thresholdText = new Text("threshold = " + gThreshold);
        Slider slider = new Slider(0, 255, gThreshold);
        slider.valueProperty().addListener((observable, oldValue, newValue) -> {
            gThreshold = newValue.intValue();
            Platform.runLater(() -> thresholdText.setText("threshold = " + gThreshold));
        });
        slider.setOnMouseReleased(event -> {
            imageProcess(srcImg);
        });
        FlowPane bottomControl = new FlowPane();
        bottomControl.getChildren().addAll(imageChooser, thresholdText, slider);
        bottomControl.setPrefHeight(50);
        BorderPane root = new BorderPane();
        imageView = new ImageView();
        root.setCenter(imageView);
        root.setBottom(bottomControl);
        Scene scene = new Scene(root, DEFAULT_WIDTH, DEFAULT_HEIGHT + 50);
        stage.setScene(scene);
        stage.setTitle("Example5-Derivative");
        stage.setResizable(false);
        stage.show();
    }
}
